# Author: Chris Moyer
# Basic Authentication version of the AuthHandlers
import re
import sys
import os, os.path

import urllib

import marajo
from marajo.appengine.handlers import RequestHandler
from marajo.appengine.ext.webapp import status, template
from marajo.appengine.api.users import User
from boto.exception import SDBResponseError

import logging
log = logging.getLogger("marajo.handlers.auth.basic")

import marajo.appengine.handlers.auth

marajo.config['handlers'].append( { "url": "/_ah/login", "handler": "marajo.appengine.handlers.auth.basic.LoginHandler" })
marajo.config['handlers'].append( { "url": "/_ah/janrain/login", "handler": "marajo.appengine.handlers.auth.janrain.LoginHandler" })

class LoginHandler(RequestHandler):
	"""
	Start off the login process
	"""

	def get(self):
		template_values = {}
		template_values['application'] = marajo.config.get("application")
		template_values['fields'] = [ 
			{"name": "user", "type": "text", "title": "Username", "value": self.request.GET.get("username", "")}, 
			{"name": "password", "type": "password", "title": "Password"},
			{"name": "continue", "type": "hidden", "value": self.request.GET.get("continue", "/")} 
			]
		template_values['login_url'] = "/_ah/login"
		self.response.write(template.render('login.tmpl', template_values))

	def post(self):
		"""
		Verify Basic authentication
		"""
		#TODO: Notify on failure
		#TODO: Only allow x number of login attempts per IP

		#TODO: Clean this up
		auth_domain = marajo.config.get("auth_domain")
		if auth_domain:
			import boto
			sdb = boto.connect_sdb()
			try:
				User._manager.domain = sdb.get_domain(auth_domain)
			except SDBResponseError:
				User._manager.domain = sdb.create_domain(auth_domain)


		username = self.request.POST.get("user")
		password = self.request.POST.get("password")
		if username:
			log.info("Login Attempt: %s" % username)
			try:
				user = User.find(username = username).__iter__().next()
			except StopIteration:
				pass
			else:
				if (user.password == password):
					self.session['user'] = user.id
					return self.redirect(self.request.get("continue", "/"))
		return self.get()
